package com.camartsApp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.camartsApp.dto.PhotoFootprintDTO;
import com.camartsApp.dto.PhotoInfoDTO;
import com.camartsApp.entity.Photo;
import com.camartsApp.mapper.PhotoMapper;
import com.camartsApp.service.IPhotoService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 照片服务实现类
 */
@Service
public class IPhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements IPhotoService {

    @Override
    public List<PhotoFootprintDTO> getUserPhotoFootprints(String userId) {
        List<Photo> photos = baseMapper.findFootprintsByUserId(userId);
        return photos.stream()
                .map(photo -> new PhotoFootprintDTO(photo.getId(), photo.getLatitude(), photo.getLongitude(), photo.getUrl(), photo.getTakenAt()))
                .collect(Collectors.toList());
    }

    @Override
    public List<PhotoInfoDTO> getPhotosByLocation(String userId, Double minLat, Double minLng, Double maxLat, Double maxLng) {
        List<Photo> photos = baseMapper.findPhotosByLocationRange(userId, minLat, minLng, maxLat, maxLng);
        double a = (maxLng - minLng) / 2.0, b = (maxLat - minLat) / 2.0; //椭圆长短轴
        double centerLat = (maxLat + minLat) / 2.0, centerLng = (maxLng + minLng) / 2.0; //椭圆中心经纬度
        List<Photo> filteredPhotos = photos.stream()
                .filter(photo -> (Math.pow(photo.getLatitude().doubleValue() - centerLat, 2) / (b * b) +
                        Math.pow(photo.getLongitude().doubleValue() - centerLng, 2) / (a * a)) <= 1.0) // 椭圆公式判定条件
                .toList();
        return filteredPhotos.stream()
                .map(photo -> new PhotoInfoDTO(
                        photo.getId(),
                        photo.getUrl(),
                        photo.getLatitude(),
                        photo.getLongitude()
                ))
                .collect(Collectors.toList());
    }
}